package com.zhihesj.anan.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhihesj.anan.message.Message;
import com.zhihesj.anan.message.MessageCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author anan.
 * @version 1.0
 * @create 2020-06-27 17-43
 */
@Slf4j
@Component
public class JwtLogoutSuccessHandler implements LogoutSuccessHandler {
    private static Logger logger = LoggerFactory.getLogger(JwtLogoutSuccessHandler.class);

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.write(objectMapper.writeValueAsString(Message.success(MessageCodeEnum.LOGOUT_SUCCESS)));
        out.flush();
        out.close();
        logger.info("退出成功");
    }
}
